package com.jiao.table.entity;

import com.jiao.comm.exception.LoadException;
import com.jiao.table.config.CacheDataLoad;
import lombok.Data;
import lombok.SneakyThrows;
import java.util.Map;
import java.util.UUID;



/**
 * @Author: vincent.jiao
 * @Date: 2021/4/29
 */
@Data
public class CacheCommand<T> {
    /** 实际存储数据  */
    private T data;

    /** 表名 */
    private String tableName;

    /** 表名key的全路径 */
    private String tableNameKey;

    /** 主键值 */
    private Long primaryKeyValue;

    /** 索引key的全路径， 与值 */
    private String mateDataBitMapKey;

    /** 索引key的全路径， 与值 */
    private Map<String, Object> indexMap;

    //元数据key
    private String mateDataVersionKey;
    private String mateDataVersionValue;

    private String mateDataMaxIdKey;

    /** 元数据索引的全路径， 与值 */
    private Map<String, Object> mateDataIndexMap;


    public CacheCommand(){
        mateDataVersionValue = UUID.randomUUID().toString();
    }

    @SneakyThrows
    public static CacheCommand newCacheCommand(Object value){
        TableInfo tableInfo = CacheDataLoad.getTableInfo(value.getClass());

        if (tableInfo == null) {
            return null;
        }

        if(tableInfo.getPrimaryKeyField() == null) {
            throw new LoadException(tableInfo.getTableName() + " 没有指定主键");
        }

        CacheCommand command = new CacheCommand();
        command.setData(value);
        command.setTableName(tableInfo.getTableName());

        tableInfo.getPrimaryKeyField().setAccessible(true);
        command.setPrimaryKeyValue((Long) tableInfo.getPrimaryKeyField().get(value));
        command.setTableNameKey(tableInfo.getTableNameKey());
        command.setIndexMap(tableInfo.getAllIndexKVMap(value));
        command.setMateDataBitMapKey(tableInfo.getMateDataBitMapKey());

        command.setMateDataVersionKey(tableInfo.getMateDataVersionKey());
        command.setMateDataMaxIdKey(tableInfo.getMateDataMaxIdNumKey());
        command.setMateDataIndexMap(tableInfo.getMateDataAllIndexKVMap(value));

        return command;
    }
}
